package es.cazadoresmadridejos.beans.dao.event.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import es.cazadoresmadridejos.beans.dao.event.EventDao;
import es.cazadoresmadridejos.common.bean.dao.impl.DaoImpl;
import es.cazadoresmadridejos.model.Event;
import es.cazadoresmadridejos.model.Event.EventType;

@SuppressWarnings("unchecked")
@Repository("eventDao")
public class EventDaoImpl extends DaoImpl<Event> implements EventDao{

	@Override
	public Event newInstance() {
		return new Event();
	}

	@Override
	public void deleteByExample(Event event) {
		List<Event> events = (List<Event>) getHibernateTemplate().findByExample(event);
		for (Event event2 : events) {
			getHibernateTemplate().delete(event2);
		}
	}

	@Override
	public List<Event> findAllByType(final EventType type, final Long idReason) {
		return (List<Event>) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				StringBuilder hql = new StringBuilder();
				hql.append("select e ")
					.append(" from Event e ")
					.append(" where e.type = :type ")
					.append(" and e.reason.id = :idReason ")
					.append("");
				Query query = session.createQuery(hql.toString());
				query.setParameter("type", type);
				query.setLong("idReason", idReason);

				return query.list();
			}
		});
	}

}
